/*
 * Copyright (c) 2009-2013 EvTech Project
 * All rights reserved.
 * 
 * This file is part of Game packet.
 *
 * Game packet is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or 
 * (at your option) any later version.
 *
 * Game packet is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Game packet.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package fi.honkalampisaatio.game.selection;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.EventObject;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.swing.AbstractButton;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;

import fi.honkalampisaatio.game.xml.NameImageData;

public class UserCountSelection extends JPanel {

	private static final long serialVersionUID = 1503746298031941436L;

	public static final String FILEPATH = "./settings/usercountsettings.xml";
	
	private SelectionListener listener = null;
	
	protected int iconHeight = 80;
	protected int iconWidth = 100;

	private boolean isExitButton;

	public UserCountSelection(boolean isExitButton) {
		this.isExitButton = isExitButton;
	}


	public void setForeground(Color color)
	{
		super.setForeground(color);
		Component[] compList = this.getComponents();
		for(int i=0;i<compList.length;i++)
		{
			compList[i].setForeground(color);
		}
	}

	public void setFont(Font font)
	{
		super.setFont(font);
		Component[] compList = this.getComponents();
		for(int i=0;i<compList.length;i++)
		{
			float fontSize = 12;
			if(compList[i] instanceof JButton)
			{
				fontSize = ((JButton)compList[i]).getFont().getSize2D();
			}
			compList[i].setFont(font.deriveFont(fontSize));
		}
	}
	
	/**
	 * Generoidaan nappi
	 * @param file
	 */
	private Component generateSelectionButton(NameImageData data, int i) {
		JButton btn = null;
		ImageIcon btnIcon = createImageIcon(data.getImage(), data.getName());
		if(btnIcon!=null) {
			btn = new JButton(data.getName(), btnIcon);
		}
		else {
			btn = new JButton(data.getName());
		}
		final int count = i;
		btn.addActionListener(
			    new ActionListener() {
			        public void actionPerformed(ActionEvent e) {
			            btnClicked(e, count);
			        }
			    }
		);
		btn.setFocusable(false);
		btn.setVerticalTextPosition(AbstractButton.BOTTOM);
		btn.setHorizontalTextPosition(AbstractButton.CENTER);
		
		return btn;
	}

	/** Returns an ImageIcon, or null if the path was invalid. */
	protected ImageIcon createImageIcon(String path, String description) {
		int width, height;
		try {
			BufferedImage img = ImageIO.read(new File(path));
			if(img.getWidth()/this.iconWidth > img.getHeight()/this.iconHeight) {
				width = this.iconWidth;
				height = -1;
			}
			else {
				width = -1;
				height = this.iconHeight;
			}
	        return new ImageIcon(img.getScaledInstance(width, height, 
	        		Image.SCALE_FAST), description);
		} catch (IOException e) {
	        System.err.println("Couldn't create icon: " + path);
			return null;
		}
	}

	protected void btnClicked(ActionEvent e, int count) {
		UserCountSelectionEvent se = new UserCountSelectionEvent(this, count);
		this.fireSelectionEvent(se);
	}
	
	public void addSelectionListener(SelectionListener  listener) {
		this.listener = listener;
	}
	
	public void removeSelectionListener(SelectionListener listener) {
		if (this.listener == listener) {
			this.listener = null;
		}
	}
	
	private void fireSelectionEvent(EventObject se) {
		if (this.listener != null)
			this.listener.selectionEventOccurred(se);
	}

	private JButton createExitButton()
	{
		JButton exitButton;
		ImageIcon btnIcon = createImageIcon("./settings/exitbutton.gif", "Lopeta peli");
		if(btnIcon!=null) {
			exitButton = new JButton("Lopeta peli", btnIcon);
		}
		else {
			exitButton = new JButton("Lopeta peli");
		}
		exitButton.setFocusable(false);
		exitButton.setVerticalTextPosition(AbstractButton.BOTTOM);
		exitButton.setHorizontalTextPosition(AbstractButton.CENTER);
		exitButton.addActionListener(
			    new ActionListener() {
			        public void actionPerformed(ActionEvent e) {
						System.exit(0);
			        }
			    }
		);
		
		return exitButton;
	}

	public void setData(ArrayList<NameImageData> usercountList) {
		this.removeAll();
		this.setLayout(new BorderLayout());
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
	    int gridColumns = (int)(Math.sqrt(usercountList.size())+1);
	    if(isExitButton)
	    {
			this.iconHeight = (int) (screenSize.height * 0.08f);
			this.iconWidth = (int) (screenSize.width * 0.08f);
		    JPanel controlButtonPanel = new JPanel();
		    this.add(controlButtonPanel, BorderLayout.PAGE_START);
		    controlButtonPanel.setLayout(new BorderLayout());
		    controlButtonPanel.add(createExitButton(), BorderLayout.LINE_END);
	    }
	    JPanel panel = new JPanel();
	    this.add(panel, BorderLayout.CENTER);
	    panel.setLayout(new GridLayout(gridColumns, gridColumns));
		this.iconHeight = (int) (screenSize.height * 0.8f / gridColumns);
		this.iconWidth = (int) (screenSize.width * 0.8f / gridColumns);
	    
		Iterator<NameImageData> it = usercountList.iterator();
		int i = 0;
		while(it.hasNext()) {
			NameImageData data = it.next();
			i++;
			panel.add(generateSelectionButton(data, i));
		}
	}
}
